<template>
  <div class="debug-view">
    <h1>权限调试页面</h1>

    <el-card class="info-card">
      <template #header>
        <h3>认证状态</h3>
      </template>
      <p><strong>是否已登录:</strong> {{ isAuthenticated }}</p>
      <p><strong>Token:</strong> {{ token ? "有效" : "无" }}</p>
    </el-card>

    <el-card class="info-card">
      <template #header>
        <h3>用户信息</h3>
      </template>
      <pre>{{ JSON.stringify(user, null, 2) }}</pre>
    </el-card>

    <el-card class="info-card">
      <template #header>
        <h3>用户角色</h3>
      </template>
      <pre>{{ JSON.stringify(userRoles, null, 2) }}</pre>
    </el-card>

    <el-card class="info-card">
      <template #header>
        <h3>权限测试</h3>
      </template>
      <p><strong>是否为管理员:</strong> {{ hasAdminRole }}</p>
      <p><strong>管理员按钮应该显示:</strong> {{ hasAdminRole ? "是" : "否" }}</p>
    </el-card>

    <el-card class="info-card">
      <template #header>
        <h3>操作</h3>
      </template>
      <el-button @click="refreshUserInfo">刷新用户信息</el-button>
      <el-button @click="clearAuth">清除认证</el-button>
      <el-button type="primary" @click="testAdminAccess">测试管理员访问</el-button>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { computed } from "vue";
import { useStore } from "vuex";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";

const store = useStore();
const router = useRouter();

// 计算属性
const isAuthenticated = computed(() => store.getters["auth/isAuthenticated"]);
const user = computed(() => store.getters["auth/user"]);
const userRoles = computed(() => store.getters["auth/userRoles"]);
const token = computed(() => store.getters["auth/token"]);

// 检查管理员权限
const hasAdminRole = computed(() => {
  const roles = userRoles.value;
  console.log("Debug页面检查管理员权限，角色:", roles);

  if (!roles || roles.length === 0) {
    return false;
  }

  return roles.some((role: any) => {
    const roleName = role.name || role.roleName || role;
    if (typeof roleName === "string") {
      const upperRole = roleName.toUpperCase();
      return upperRole === "ADMIN" || upperRole === "ROLE_ADMIN";
    }
    return false;
  });
});

// 刷新用户信息
const refreshUserInfo = async () => {
  try {
    await store.dispatch("auth/fetchUserInfo");
    ElMessage.success("用户信息已刷新");
  } catch (error) {
    ElMessage.error("刷新失败: " + error);
  }
};

// 清除认证
const clearAuth = () => {
  store.commit("auth/CLEAR_AUTH");
  ElMessage.info("认证信息已清除");
  router.push("/login");
};

// 测试管理员访问
const testAdminAccess = () => {
  if (hasAdminRole.value) {
    router.push("/admin");
  } else {
    ElMessage.error("您没有管理员权限");
  }
};
</script>

<style scoped lang="scss">
.debug-view {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;

  .info-card {
    margin-bottom: 20px;

    pre {
      background: #f5f5f5;
      padding: 10px;
      border-radius: 4px;
      overflow-x: auto;
      font-size: 12px;
    }
  }
}
</style>
